import { defineStore } from 'pinia';
import { reactive, computed } from 'vue';
import _ from "lodash";
// import validate from "@/libs/validate/validate";

export const useStore = defineStore('insure', () => {
  // 保险内容
  const content = reactive({
    // 单人保额
    unit_amount: 3500000,
    // // 单人保费(<50岁)
    // unit_premium_below50: 99,
    // 单人保费(<50岁)
    unit_premium_below50: 0.01,
    // 单人保费(≥50岁)
    unit_premium_higher50: 149,
    // 应用类型
    app_type: 'wechat',
  })

  // 被保人单项
  const insured_item = {
    identity: {},
    name: '',
    id_type: '111', //默认身份证，后端code为111
    id_no: '',
    address: [],
    mobile: '',
  };

  // 表单
  const form = reactive({
    number: '',
    applicant: {
      name: '',
      id_type: '111', //默认身份证，后端code为111
      id_no: '',
      address: [],
      mobile: '',
      code: '',
    },
    insured: [] as any[],
  })

  // 添加被保人
  const addInsured = () => {
    form.insured.push(_.cloneDeep(insured_item));
  }

  // 移除被保人
  const removeInsured = (idx: number) => {
    form.insured.splice(idx, 1);
  }

  // 默认添加一个被保人
  addInsured();

  // 提交参数
  const params = computed(() => {
    let number = form.number;
    let sum_amount = Number((content.unit_amount * form.insured.length).toFixed(0));
    let sum_premium = sumPremium();
    let app_type = content.app_type;
    let applicant: any = _.cloneDeep(form.applicant);
    applicant.address = applicant.address?.length > 0 ? applicant.address.join(",") : '';
    let code = applicant.code;
    delete applicant.code;
    let insured = _.cloneDeep(form.insured).map((x: any) => {
      x.address = x.address?.length > 0 ? x.address.join(",") : '';
      x.identity = x.identity?.dict_value || '';
      return x;
    });
    return {
      number,
      sum_amount,
      sum_premium,
      app_type,
      applicant,
      code,
      insured,
    }
  })

  // 总保费
  const sumPremium = () => {
    let num = 0;
    const nDate = new Date();
    nDate.setFullYear(nDate.getFullYear() - 50);
    const nTimeStamp = nDate.getTime();
    form.insured.forEach((item: any) => {
      // if (validate.test(item.id_no, 'idcard')) {
      //   const mDate_str = `${item.id_no.slice(6, 10)}/${item.id_no.slice(10, 12)}/${item.id_no.slice(12, 14)}`;
      //   const mDate = new Date(mDate_str);
      //   const mTimeStamp = mDate.getTime();
      //   if (mTimeStamp <= nTimeStamp) {
      //     num += content.unit_premium_higher50;
      //   } else {
      //     num += content.unit_premium_below50;
      //   }
      // }
    })
    return num;
  }

  // 设置推荐号number
  const setNumber = (str: string) => {
    form.number = str;
  }

  return {
    form,
    params,
    setNumber,
    addInsured,
    removeInsured,
  }
})